package com.futu.intelligence.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.futu.intelligence.entity.Attraction;
import com.futu.intelligence.entity.Favorite;
import com.futu.intelligence.entity.TravelPlan;
import com.futu.intelligence.entity.TravelPlanDetail;
import com.futu.intelligence.mapper.AttractionMapper;
import com.futu.intelligence.mapper.FavoriteMapper;
import com.futu.intelligence.mapper.TravelPlanDetailMapper;
import com.futu.intelligence.mapper.TravelPlanMapper;
import com.futu.intelligence.service.TravelService;
import com.futu.intelligence.utils.AMapUtil;
import com.futu.intelligence.utils.DeepSeekUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TravelServiceImpl implements TravelService {

    @Autowired
    private DeepSeekUtil deepSeekUtil;

    @Autowired
    private AMapUtil aMapUtil;

    @Autowired
    private TravelPlanMapper travelPlanMapper;

    @Autowired
    private TravelPlanDetailMapper travelPlanDetailMapper;

    @Autowired
    private AttractionMapper attractionMapper;

    @Autowired
    private FavoriteMapper favoriteMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional
    public TravelPlan generatePlan(String city, int days, Long userId) {
        try {
            // 1. 使用DeepSeek生成旅游计划
            String aiResponse = deepSeekUtil.generateTravelPlan(city, days);
            if (aiResponse == null || aiResponse.trim().isEmpty()) {
                throw new RuntimeException("AI返回内容为空，无法生成旅游计划");
            }
            // 2. 解析JSON响应
            JsonNode planJson = objectMapper.readTree(aiResponse);

            // 3. 创建旅游计划
            TravelPlan plan = new TravelPlan();
            plan.setUserId(userId);
            plan.setTitle(city + days + "天旅游计划");
            plan.setCity(city);
            plan.setDays(days);
            plan.setCreateTime(new Date());

            // 4. 保存旅游计划
            travelPlanMapper.insert(plan);

            // 5. 处理每一天的计划
            List<TravelPlanDetail> details = new ArrayList<>();
            JsonNode daysNode = planJson.get("plan");

            for (JsonNode dayNode : daysNode) {
                int dayNum = dayNode.get("day").asInt();
                JsonNode attractionsNode = dayNode.get("attractions");

                int order = 1;
                for (JsonNode attrNode : attractionsNode) {
                    String attrName = attrNode.get("name").asText();
                    String description = attrNode.get("description").asText();

                    // 6. 查找或创建景点
                    Attraction attraction = attractionMapper.findByName(attrName, city);
                    if (attraction == null) {
                        // 使用高德地图API查找景点信息
                        String searchResult = aMapUtil.searchAttraction(attrName, city);
                        Map<String, Double> location = aMapUtil.parseLocation(searchResult);

                        if (location != null) {
                            attraction = new Attraction();
                            attraction.setName(attrName);
                            attraction.setCity(city);
                            attraction.setDescription(description);
                            attraction.setLongitude(location.get("longitude"));
                            attraction.setLatitude(location.get("latitude"));

                            // 从高德API结果中提取地址
                            JsonNode searchJson = objectMapper.readTree(searchResult);
                            if (searchJson.has("pois") && searchJson.get("pois").isArray()
                                && searchJson.get("pois").size() > 0) {

                                JsonNode firstPoi = searchJson.get("pois").get(0);
                                if (firstPoi.has("address")) {
                                    attraction.setAddress(firstPoi.get("address").asText());
                                } else {
                                    attraction.setAddress(city + attrName);
                                }
                            } else {
                                attraction.setAddress(city + attrName);
                            }

                            attractionMapper.insert(attraction);
                        }
                    }

                    if (attraction != null) {
                        // 7. 创建旅游计划详情
                        TravelPlanDetail detail = new TravelPlanDetail();
                        detail.setPlanId(plan.getId());
                        detail.setDayNum(dayNum);
                        detail.setAttractionId(attraction.getId());
                        detail.setVisitOrder(order++);

                        travelPlanDetailMapper.insert(detail);
                        details.add(detail);
                    }
                }
            }

            plan.setDetails(details);
            return plan;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public TravelPlan getPlanDetail(Integer planId) {
        // 1. 获取旅游计划
        TravelPlan plan = travelPlanMapper.findById(planId);
        if (plan == null) {
            return null;
        }

        // 2. 获取计划详情
        List<TravelPlanDetail> details = travelPlanDetailMapper.findByPlanId(planId);

        // 3. 获取所有景点ID
        List<Integer> attractionIds = new ArrayList<>();
        for (TravelPlanDetail detail : details) {
            attractionIds.add(detail.getAttractionId());
        }

        // 4. 批量查询景点信息（防止空列表导致SQL错误）
        List<Attraction> attractions = new ArrayList<>();
        if (!attractionIds.isEmpty()) {
            attractions = attractionMapper.findByIds(attractionIds);
        }
        Map<Integer, Attraction> attractionMap = new HashMap<>();
        for (Attraction attraction : attractions) {
            attractionMap.put(attraction.getId(), attraction);
        }

        // 5. 关联景点信息
        for (TravelPlanDetail detail : details) {
            detail.setAttraction(attractionMap.get(detail.getAttractionId()));
        }

        plan.setDetails(details);
        return plan;
    }

    @Override
    public boolean favoritePlan(Long userId, Integer planId) {
        Favorite existing = favoriteMapper.findByUserIdAndPlanId(userId, planId);
        if (existing != null) {
            return true; // 已经收藏过了
        }

        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setPlanId(planId);
        favorite.setCreateTime(new Date());

        return favoriteMapper.insert(favorite) > 0;
    }

    @Override
    public boolean cancelFavorite(Long userId, Integer planId) {
        return favoriteMapper.delete(userId, planId) > 0;
    }

    @Override
    public List<Favorite> getUserFavorites(Long userId) {
        List<Favorite> favorites = favoriteMapper.findByUserId(userId);
        System.out.println("原始收藏数量: " + favorites.size());
        
        // 获取对应的旅游计划信息
        for (Favorite favorite : favorites) {
            TravelPlan plan = travelPlanMapper.findById(favorite.getPlanId());
            if (plan != null) {
                // 设置旅游计划的基本信息
                favorite.setPlan(plan);
                System.out.println("关联计划 ID: " + plan.getId() + ", 标题: " + plan.getTitle() + ", 城市: " + plan.getCity() + ", 天数: " + plan.getDays());
            } else {
                System.out.println("未找到计划 ID: " + favorite.getPlanId());
            }
        }
        
        return favorites;
    }

    @Override
    public List<Attraction> getHotAttractions() {
        // 返回一些热门景点，这里可以根据实际需求调整
        return attractionMapper.findHotAttractions();
    }
}
